# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


from typing import *


class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:

        h = {}
        for i, v in enumerate(inorder):
            h[v] = i

        def f(l, L, s):
            if s == 0:
                return None
            v = preorder[l]
            root = TreeNode(v)
            i = h[v]
            root.left = f(l + 1, L, i - L)
            root.right = f(l + i - L + 1, i + 1, s - i + L - 1)
            return root

        return f(0, 0, len(preorder))
